package com.chisheng.caa.service.impl;

import com.chisheng.caa.config.RedisCacheNames;
import com.chisheng.caa.pojo.LoginUserDetails;
import com.chisheng.caa.pojo.dto.LoginUserDTO;
import com.chisheng.caa.pojo.dto.UserInfoDTO;
import com.chisheng.caa.service.UserService;
import com.chisheng.caa.util.BeanUtil;
import com.chisheng.caa.util.JwtUtil;
import com.chisheng.caa.util.RedisCacheUtil;
import com.chisheng.caa.util.SecurityUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Resource
    private RedisCacheUtil redisCacheUtil;

    @Resource
    private AuthenticationManager authenticationManager;

    @Override
    public String login(LoginUserDTO user) {
        Authentication auth = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());
        Authentication authentication = authenticationManager.authenticate(auth);
        LoginUserDetails userDetails = (LoginUserDetails) authentication.getPrincipal();
        long expiry = TimeUnit.DAYS.convert(JwtUtil.EXPIRY, TimeUnit.MILLISECONDS);
        String cacheKey = getCacheKey(userDetails);
        redisCacheUtil.setCacheObject(cacheKey, userDetails, expiry, TimeUnit.DAYS);
        return JwtUtil.createToken(userDetails.getUser().getUserId());
    }

    @Override
    public UserInfoDTO getUserInfo() {
        LoginUserDetails userDetails = SecurityUtil.getPrincipal();
        return BeanUtil.copyProperties(userDetails.getUser(), UserInfoDTO.class);
    }

    @Override
    public boolean logout() {
        try {
            LoginUserDetails userDetails = SecurityUtil.getPrincipal();
            redisCacheUtil.deleteObject(getCacheKey(userDetails));
            return true;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return false;
        }
    }

    /**
     * 获取访问键
     */
    private String getCacheKey(LoginUserDetails userDetails) {
        return RedisCacheNames.OAUTH_PREFIX + userDetails.getUser().getUserId();
    }

}
